/**
 * 
 */// A singleton utility class 

var Util = function($) {	
	
	/*
	 * @param - objArray, an array of object to be sorted.
	 * 			criteria, object property to be sorted by.
	 *          asc, boolean value to indicate ascending order or descending order.
	 * 
	 * @return - none, a sorted array of object by criteria in ascending order or descending order.
	 */
	sortByCriteria = function(objArray, criteria, asc) {
			
			if (objArray instanceof Array) {
				objArray.sort(function(value1, value2){					
					// Modified code to make string sorting case insensitive.
					var value1 = value1[criteria];
					var value2 = value2[criteria];

					value1 = typeof(value1) == 'string'?value1.toLowerCase():value1;
					value2 = typeof(value2) == 'string'?value2.toLowerCase():value2;
					// Moves the null values to the last
					if (value1 == null && value2 == null) return 0;
					if (value1 == null) return 1;
					if (value2 == null) return -1;
					if (value1 < value2) {
						if (asc) return -1;						
						return 1;
					}
					else if (value1 > value2) {
						if (asc) return 1;						
						return -1;
					}
					else {
						return 0;
					}
				});
			}
	 },
	 insertCommas = function(amount){
		 //index for decimal position
		 	var index=amount.indexOf('.');
			if(index >0){
				var max_index=index+3;
				amountDecimal=amount.substring(index,max_index);
				amount=amount.substring(0,index);
				amount = amount.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
				amount=amount+amountDecimal
			}else{
				amount = amount.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
			}
			return amount;
		},
		/*
		 * @param - value, number to be formatted.
		 * 		  - options, customize options.
		 *		  - delimiter, character to insert.
		 * @return - string, a string representative of the number formatted * 100.0 %.
		 * 		   - For an example, return 1,141.12%
		 */
		formatNumberPercentageWithDelimeter = function(value, options) {
			if (typeof value == "number" && isValidNumber(value)) {
				
				var options = $.extend({decimals: 1,
										thousands: ',',
										sign: true
										}, options);			
				var number = new Number(value);					
				// If it's negative, create a negative sign and make it a positive number
				if (number < 0) {
					var sign = '-';
					number = number * -1;
				} else {
					sign = '';
				}				
				number = number.toFixed(options.decimals);								
				number = insertNumberDelimiter(number, options.thousands);				
				return (sign ? sign + number : number);										
			} else if (typeof value == "number" && !isValidNumber(value)){
				return "N/A";				
			}			
			return "N/A";
		},
	String.prototype.replaceAll = function(stringToFind,stringToReplace) {
	    var temp = this;
	    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    },
    getQryStringArgs = function(qryStr) {			
		var qry = qryStr || (location.search.length > 0 ? location.search.substring(1) : ""),
		args = {}, items = qry.split("&"), item = null, name = null, value = null, i;
		
		for ( i = 0; i < items.length; i += 1) {
			item = items[i].split("=");
			name = decodeURIComponent(item[0]);
			value = decodeURIComponent(item[1]);
			args[name] = value;
		}			
		return args;
	},
	trim  =  function(value) {
	  var temp = value.toString();
	  var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
	  if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
		var obj = / +/g;
	    temp = temp.replace(obj, " ");
	    if (temp == " ") { temp = ""; }
	    return temp;
   },
	isValidNumber = 	function(value) {
		if (value == -999999999) {
			return false;	
		}
		
		return true;
	},
	/* To format number with decimals. 
	 *@param  - value, number to be formatted with decimals.
	 * 		  - options
	 *@return - string, a string representative of the number with decimals.
	 */
	 formatNumberWithDecimals = function(value, options) {
		 options = parseInt(options/1 || 0)
	   	 if (options<0 || options>20) // next line was throw ...
	   	 if (isNaN(value)) return "NaN"
	   	       var s = value<0 ? "-" : "", x = Math.abs(value)
	   	 if (x>Math.pow(10,21)) return s + x.toString()
	   	      var m = Math.round(x*Math.pow(10,options)).toString()
	   	 if (!options) return s + m
	   	 while (m.length<=options) m = "0" + m
	   		return s + m.substring(0,m.length-options)+"."+m.substring(m.length-options)
     },
     /*
		 * @param - value, number to insert.
		 *        - delimiter, character to insert.
		 *        
		 * @return - string, a number with delimiter every thousandth position..
		 */
		insertNumberDelimiter = function(value, delimiter) {
			if (value == null) {
				return "";
			}
			
//			if (typeof value != "number") {
//				return "";
//			}
			var length = value.length;
			var valueStr = value + "";
			var decimalPoint = valueStr.indexOf(".");
			var counter = 0;
			var returnValue = "";
		
			if (decimalPoint == -1) {
				for (var i = length - 1; i >= 0; i--) {
					returnValue = value.charAt(i) + ((counter > 0 && counter % 3 == 0) ? delimiter : '') + returnValue;				
					counter++;
				} 
			} else {	
				
				// Get decimals points including the dot
				for (var i = decimalPoint; i < length; i++) {
					returnValue += value.charAt(i);	
				}
				
				// Get anything before decimal point and append decimal numbers to it
				for (var i = decimalPoint - 1; i >= 0; i--) {				
					returnValue = valueStr.charAt(i) + ((counter > 0 && counter % 3 == 0) ? delimiter : '') + returnValue;				
					counter++;
				}
			}
			
			return returnValue;		
		},
		/* source p4p/js/Util.js
		 * @param - value, number to be formatted.
		 * 		  - options, customize options.
		 *		  - delimiter, character to insert.
		 * @return - string, a string representative of the number formatted * 100.0 %.
		 * 		   - For an example, return 1,141.12%
		 */
		formatNumberPercentageWithCommaDelimeter = function(value, options) {
			if (typeof value == "number" && isValidNumber(value) && value != -888888888) {
				
				var options = $.extend({decimals: 1,
										thousands: ',',
										sign: true
										}, options);			
				var number = new Number(value);					
				// If it's negative, create a negative sign and make it a positive number
				if (number < 0) {
					var sign = '-';
					number = number * -1;
				} else {
					sign = '';
				}		
				
				number = number * 100.0;
				number = formatNumberWithDecimals(number,options.decimals);
				number = insertNumberDelimiter(number, options.thousands);	
				if( number != null && number == -0 && number == 0 ){
					number = '0.0';
					sign = '';
				}
				return (sign ? sign + number : number) + "%";										
			} else if (typeof value == "number" && !isValidNumber(value)){
				return "N/A";				
			}			
			return "N/A";
		},
	/* source p4p/js/Util.js
	 * @param - value, number to be formatted.
	 * 		  - options, customize options.
	 * 
	 * @return - string, a string representative of the number formatted.
	 *  	   - "N/A", If the number is out of range (-999999999).
	 *                  Or if the given value is not a number.
	 */
	formatNumber = function(value, options) {
		
		if (typeof value == "number" && isValidNumber(value)) {
			
			var options = $.extend({decimals: 2,
									thousands: ',',
									sign: true
									}, options);
		
			var number = new Number(value);	
			
			// If it's negative, create a negative sign and make it a positive number
			if (number < 0) {
				var sign = '-';
				number = number * -1;
			} else {
				sign = '';
			}
			number = formatNumberWithDecimals(number,options.decimals);
			number = insertNumberDelimiter(number, options.thousands);
			return (sign ? sign + number : number);
									
		} else if (typeof value == "number" && !isValidNumber(value)){
			return "N/A";				
		}
		
		return "N/A";
	},

	//To format a number with out decimals and without rounding
	formatNumberWithoutRounding = function(num){
		if (typeof num == "number" && isValidNumber(num)) {
			num = num +'';
			var ary = num.split(".");
			var formatedNumber = Number(ary[0]);
			if (typeof formatedNumber == "number" && isValidNumber(formatedNumber)) {
				var value = this.formatNumber(formatedNumber, {decimals : 0});
				return value;
			}else{
				return "N/A";
			}
		}else if(typeof num == "number" && !isValidNumber(num)){
			return "N/A";
		}
		return "N/A";
	},
	/* 
	 * @param - value, number to be formatted.
	 * 		  - options, customize options.
	 * 
	 * @return - string with dollar, a string representative of the number formatted eg: $1.44, if negative num: ($1.44).
	 *  	   - "N/A", If the number is out of range (-999999999).
	 *                  Or if the given value is not a number.
	 */
	formatNumberWithParenthesis = function(value, options) {
		
		if (typeof value == "number" && isValidNumber(value)) {
			
			var options = $.extend({decimals: 2,
				thousands: ',',
				sign: true
			}, options), 
			number = new Number(value),
			sign = false;
			
			// If it's negative, create a negative sign and make it a positive number
			if (number < 0) {
				sign = true;
				number = number * -1;
			} else {
				sign = false;
			}
			number = formatNumberWithDecimals(number, options.decimals);
			number = insertNumberDelimiter(number, options.thousands);
			number = options.dollar + number
			return (sign ? "(" + number + ")" : number);
		} else if (typeof value == "number" && !isValidNumber(value)) {
			return "N/A";				
		}
		return "N/A";
	},
	/*
	 * @param - value, number to convert.
	 * 		  - options, customize options.
	 * 
	 * @return - String, a string representative of the number converted to money.
	 *         - "N/A", If the given value is not a number.
	 *        
	 */
	convertToMoneyForP4pIss = function(value, options) {			
		
		if (typeof value == "number") {
			
			var options = $.extend({decimals: 2,
									thousands: ',',
									dollar: '',
									unit: 1,
									sign: false
									}, options);
			
			value = value / options.unit;
			
			// If it's negative, create a negative sign and make it a positive number
			if (value < 0) {
				var sign = '-';
				value = value * -1;
			} else {
				
				sign = '';
			}
							
			value = this.formatNumber(value, options);
			
			return sign + options.dollar + value;
			
		}
		return "N/A";
	},
	/*
	 * @param - value, number to convert.
	 * 		  - options, customize options.
	 * 
	 * @return - String, a string representative of the number converted to money.
	 *         - "N/A", If the given value is out of range (-999999999).
	 * 		            Or if the given value is not a number.
	 */
	convertToMoneyWithoutSymbol = function(value, options) {			
		
		if (typeof value == "number" && isValidNumber(value)) {
			
			var options = $.extend({decimals: 2,
									thousands: ',',
									dollar: '',
									unit: 1,
									sign: false
									}, options);
			
			value = value / options.unit;
			
			// If it's negative, create a negative sign and make it a positive number
			if (value < 0) {					
				var sign = '-';
				value = value * -1;
			} else {
				
				sign = '';
			}
							
			value = this.formatNumber(value, options);
			
			return sign + options.dollar + value;
			
		} else if (typeof value == "number" && !isValidNumber(value)){
			return "N/A";				
		}
		
		return "N/A";
	},
	/* To get dollar and value based on isDollar flag
	 * 
	 * @param value ,number to convert
	 * @param isDollar , true or false
	 */
	dollarAndValue = function(value, isDollar) {
		var dollar = "$";
		if (isDollar) {
			if(value < 0 && isValidNumber(value)){
				   dollar = "-$";
				   value = value * -1;
			 }
		}
		var formattedValue = convertToMoneyWithoutSymbol(value, {decimals: 0});
		if (formattedValue != "N/A"){
			if (isDollar) {
				formattedValue = dollar + formattedValue;
			}
		}
		return formattedValue;
	},
	/*
	 * @param - value, number to convert.
	 * 		  - options, customize options.
	 * 
	 * @return - String, a string representative of the number converted to money.
	 *         - "N/A", If the given value is out of range (-999999999).
	 * 		            Or if the given value is not a number.
	 */
	 convertToMoney = function( value, options ) {			
		if ( typeof value == "number" && isValidNumber(value) ) {
			var sign = '';
			options = $.extend( {decimals: 2,
								thousands: ',',
								dollar: '$',
								unit: 1000000,
								sign: false
								}, options);
			value = value / options.unit;
			// If it's negative, create a negative sign and make it a positive number
			if (value < 0) {					
				sign = '-';
				value = value * -1;
			} else {
				sign = '';
			}
			value = this.formatNumber( value, options );
			return sign + options.dollar + value;
		} else if ( typeof value == "number" && !isValidNumber(value) ) {
			return "N/A";				
		}
		return "N/A";
	},
	/*
	 * @param - value, number to convert.
	 * 		  - options, customize options.
	 * 
	 * @return - String, a string representative of the number converted to money if negative returns "($1.44)".
	 *         - "N/A", If the given value is out of range (-999999999).
	 * 		            Or if the given value is not a number.
	 */
	convertToMoneyWithParenthesis = function( value, options ) {			
		if ( typeof value == "number" && isValidNumber(value) ) {
			var sign = false;
			options = $.extend( {decimals: 2,
				thousands: ',',
				dollar: '$',
				unit: 1000000,
				sign: false
			}, options);
			value = value / options.unit;
			// If it's negative, create a negative sign and make it a positive number
			if (value < 0) {					
				sign = true;
				value = value * -1;
			} else {
				sign = false;
			}
			value = this.formatNumber( value, options );
			value = options.dollar + value;
			return sign ? "(" + value + ")" : value;
		} else if ( typeof value == "number" && !isValidNumber(value) ) {
			return "N/A";				
		}
		return "N/A";
	},
	/*
	 * return mm/dd/yy for a millisecond (java Date.getTime())
	 */
	formatDate = function(milliseconds) {
		if (milliseconds == null) {
			return 'N/A';
		}
		try {
			var date = new Date(milliseconds);
			var monthStr = date.getMonth() + 1;
			var datestr  = date.getDate();
			var yearStr = date.getFullYear();
			var formatYear = yearStr +"";
			// formatYear = formatYear.substr(2,formatYear.length);
			if( monthStr != null && monthStr < 10){
				monthStr = "0" + monthStr;
			}
			if( datestr != null && datestr < 10 ){
				datestr = "0" + datestr;
			}
           return  monthStr + "/" + datestr + "/" + formatYear;
		} catch(e) {
			return 'N/A';
		}
	};
	/*
	 * return mmmm yyyy for a millisecond (java Date.getTime())
	 */
	formatDateMonthYear = function(milliseconds) {
		if (milliseconds == null) {
			return 'N/A';
		}
		var  MONTHS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
		try {
			var date = new Date(milliseconds);
			var monthStr = MONTHS[date.getMonth()];
			var yearStr = date.getFullYear();
			var formatYear = yearStr +"";
           return  monthStr + " " + formatYear;
		} catch(e) {
			return 'N/A';
		}
	};
	
}(jQuery);
